#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
定期监控爬虫进度的脚本
"""

import time
import subprocess
import os
from datetime import datetime

def monitor(interval=300, log_file="monitoring/progress.log"):
    """定期监控爬虫进度
    
    Args:
        interval: 检查间隔（秒）
        log_file: 日志文件路径
    """
    # 创建日志目录
    os.makedirs(os.path.dirname(log_file), exist_ok=True)
    
    print(f"开始监控爬虫进度，间隔: {interval}秒，日志文件: {log_file}")
    
    try:
        while True:
            # 运行检查脚本
            result = subprocess.run(
                ["python", "monitoring/check_progress.py"],
                capture_output=True,
                text=True
            )
            
            # 记录输出到日志文件
            with open(log_file, "a", encoding="utf-8") as f:
                f.write(f"\n===== 监控时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} =====\n")
                f.write(result.stdout)
                if result.stderr:
                    f.write(f"错误: {result.stderr}\n")
            
            print(f"已更新进度日志，下次检查将在 {interval} 秒后进行")
            
            # 等待下一次检查
            time.sleep(interval)
            
    except KeyboardInterrupt:
        print("监控已停止")
    except Exception as e:
        print(f"监控过程中出错: {e}")

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description="爬虫进度监控工具")
    parser.add_argument("-i", "--interval", type=int, default=300, help="检查间隔（秒）")
    parser.add_argument("-l", "--log", default="monitoring/progress.log", help="日志文件路径")
    
    args = parser.parse_args()
    
    monitor(interval=args.interval, log_file=args.log)
